﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BakaGit.Utils
{
    public static class RegisterFileTypeHelper
    {

        [DllImport("shell32.dll")]
        private static extern void SHChangeNotify(int wEventId, int uFlags, int dwItem1, int dwItem2);
        private const int SHCNE_ASSOCCHANGED = 0x8000000;
        private const int SHCNF_FLUSHNOWAIT = 0x2000;

        private static void UpdateExplorer()
        {
            SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSHNOWAIT, 0, 0);
        }

        private static FileTypeRegInfo MyRegInfo
        {
            get
            {
                return new FileTypeRegInfo()
                {
                    ExtendName = ".bakarepo",
                    ReferenceName = "BakaGitRepoConfig",
                    Description = "BakaGit 仓库配置",
                    IconPath = Application.ExecutablePath+"",
                    ExePath = Application.ExecutablePath
                };
            }
        }

       
        public static void RegisterOrUpdate()
        {
            var info = MyRegInfo;
            if (FileTypeRegister.FileTypeRegistered(info.ExtendName))
            {
                FileTypeRegister.UpdateFileTypeRegInfo(info);
            }
            else
            {
                FileTypeRegister.RegisterFileType(info);
            }
            UpdateExplorer();
        }

        public static void Unregister()
        {
            FileTypeRegister.UnregisterFileType(MyRegInfo);
            UpdateExplorer();
        }
    }


    /// <summary>
    /// 文件类型注册信息
    /// </summary>
    public class FileTypeRegInfo
    {
        /// <summary>  
        /// 扩展名  
        /// </summary>  
        public string ExtendName; 
        /// <summary>  
        /// 引用描述  
        /// </summary>  
        public string ReferenceName;  
        /// <summary>  
        /// 说明  
        /// </summary>  
        public string Description; 
        /// <summary>  
        /// 关联的图标  
        /// </summary>  
        public string IconPath;
        /// <summary>  
        /// 应用程序  
        /// </summary>  
        public string ExePath;

        public FileTypeRegInfo()
        {
        }
        public FileTypeRegInfo(string extendName)
        {
            this.ExtendName = extendName;
        }
    }
    public static class FileTypeRegister
    {
        private static RegistryKey ClassRoot
        {
            get
            {
                return Registry.CurrentUser.OpenSubKey("Software", true).OpenSubKey("Classes", true);
            }
        }

        /// <summary>  
        /// 使文件类型与对应的图标及应用程序关联起来
        /// </summary>          
        public static void RegisterFileType(FileTypeRegInfo regInfo)
        {
            if (FileTypeRegistered(regInfo.ExtendName))
            {
                return;
            }

            //HKEY_CLASSES_ROOT/.osf
            RegistryKey fileTypeKey = ClassRoot.CreateSubKey(regInfo.ExtendName);
            string relationName = regInfo.ReferenceName;
            fileTypeKey.SetValue("", relationName);
            fileTypeKey.Close();

            //HKEY_CLASSES_ROOT/OSF_FileType
            RegistryKey relationKey = ClassRoot.CreateSubKey(relationName);
            relationKey.SetValue("", regInfo.Description);

            //HKEY_CLASSES_ROOT/OSF_FileType/Shell/DefaultIcon
            RegistryKey iconKey = relationKey.CreateSubKey("DefaultIcon");
            iconKey.SetValue("", regInfo.IconPath);

            //HKEY_CLASSES_ROOT/OSF_FileType/Shell
            RegistryKey shellKey = relationKey.CreateSubKey("Shell");

            //HKEY_CLASSES_ROOT/OSF_FileType/Shell/Open
            RegistryKey openKey = shellKey.CreateSubKey("Open");

            //HKEY_CLASSES_ROOT/OSF_FileType/Shell/Open/Command
            RegistryKey commandKey = openKey.CreateSubKey("Command");
            commandKey.SetValue("", "\""+regInfo.ExePath + "\" \"%1\""); // " %1"表示将被双击的文件的路径传给目标应用程序
            relationKey.Close();
        }

        /// <summary>  
        /// 使文件类型与对应的图标及应用程序关联起来
        /// </summary>          
        public static void UnregisterFileType(FileTypeRegInfo regInfo)
        {
            if (!FileTypeRegistered(regInfo.ExtendName))
            {
                return;
            }

            //HKEY_CLASSES_ROOT/.osf
            ClassRoot.DeleteSubKeyTree(regInfo.ExtendName);
            //HKEY_CLASSES_ROOT/OSF_FileType
            ClassRoot.DeleteSubKeyTree(regInfo.ReferenceName);

        }


        /// <summary>  
        /// 更新指定文件类型关联信息  
        /// </summary>      
        public static bool UpdateFileTypeRegInfo(FileTypeRegInfo regInfo)
        {
            if (!FileTypeRegistered(regInfo.ExtendName))
            {
                return false;
            }

            //HKEY_CLASSES_ROOT/.osf
           

            string extendName = regInfo.ExtendName;
            string relationName = regInfo.ReferenceName;
            RegistryKey fileTypeKey = ClassRoot.CreateSubKey(regInfo.ExtendName);
            fileTypeKey.SetValue("", relationName);
            fileTypeKey.Close();
            RegistryKey relationKey = ClassRoot.OpenOrCreateSubkey(relationName);
            relationKey.SetValue("", regInfo.Description);
            RegistryKey iconKey = relationKey.OpenOrCreateSubkey("DefaultIcon");
            iconKey.SetValue("", regInfo.IconPath);
            RegistryKey shellKey = relationKey.OpenOrCreateSubkey("Shell");
            RegistryKey openKey = shellKey.OpenOrCreateSubkey("Open");
            RegistryKey commandKey = openKey.OpenOrCreateSubkey("Command");
            commandKey.SetValue("", "\""+regInfo.ExePath + "\" \"%1\"");
            relationKey.Close();
            return true;
        }

        private static RegistryKey OpenOrCreateSubkey(this RegistryKey mainKey,string subkeyName)
        {
            var key = mainKey.OpenSubKey(subkeyName,true);
            return key ?? mainKey.CreateSubKey(subkeyName,true) ;
        }


        /// <summary>  
        /// 指定文件类型是否已经注册  
        /// </summary>          
        public static bool FileTypeRegistered(string extendName)
        {
            RegistryKey softwareKey = ClassRoot.OpenSubKey(extendName);
            if (softwareKey != null)
            {
                return true;
            }
            return false;
        }
    }

}
